<template>
  <view class="container">
    <!-- 顶部卡片 -->
    <view class="top-card">
      <!-- 装饰背景 -->
      <view class="decoration-bg"></view>
      <!-- 用户信息 -->
      <view class="user-info">
        <view class="user-left" @click="!isLoggedIn ? goToLogin() : null">
          <view class="user-avatar">
            <text class="avatar-text">{{
              isLoggedIn
                ? userInfo.realName?.charAt(0) ||
                userInfo.name?.charAt(0) ||
                userInfo.username?.charAt(0) ||
                "未"
                : "未"
            }}</text>
            <view class="avatar-badge" v-if="isLoggedIn"></view>
          </view>
          <view class="user-details">
            <text class="username">{{
              isLoggedIn
                ? userInfo.realName ||
                userInfo.name ||
                userInfo.username ||
                "用户"
                : "点击登录"
            }}</text>
            <text class="user-level">{{
              isLoggedIn ? "信用优秀" : "登录后查看更多功能"
            }}</text>
          </view>
        </view>
        <view class="contract-action" @click="addContract">
          <text class="action-icon">+</text>
          <text class="action-text">新增合同</text>
        </view>
      </view>

      <!-- 金额统计 -->
      <view class="amount-stats">
        <view class="stats-header">
          <text class="stats-title">资金概览</text>
          <!-- <text class="stats-update">实时更新</text> -->
        </view>
        <view class="amount-row">
          <view class="amount-item main">
            <view class="amount-icon lend">📤</view>
            <view class="amount-content">
              <text class="amount-value">¥ {{ fundOverview.lentAmount }}</text>
              <text class="amount-label">借出总金额</text>
            </view>
          </view>
          <view class="amount-item main">
            <view class="amount-icon borrow">📥</view>
            <view class="amount-content">
              <text class="amount-value">¥ {{ fundOverview.borrowedAmount }}</text>
              <text class="amount-label">借入总金额</text>
            </view>
          </view>
        </view>
        <view class="amount-row detail">
          <view class="amount-item small">
            <text class="small-value">¥ {{ fundOverview.receivedAmount }}</text>
            <text class="small-label">已收金额</text>
          </view>
          <view class="amount-item small">
            <text class="small-value red">¥ {{ fundOverview.receivableAmount }}</text>
            <text class="small-label">待收金额</text>
          </view>
          <view class="amount-item small">
            <text class="small-value green">¥ {{ fundOverview.paidAmount }}</text>
            <text class="small-label">已还金额</text>
          </view>
          <view class="amount-item small">
            <text class="small-value">¥ {{ fundOverview.payableAmount }}</text>
            <text class="small-label">待还金额</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 合同统计标签 -->
    <view class="contract-tabs">
      <view class="tabs-scroll">
        <view class="tab-item" :class="{ active: activeTab === 'all' }" @click="switchTab('all')">
          <text class="tab-count">{{ contractStats.total }}</text>
          <text class="tab-text">全部</text>
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'waiting' }" @click="switchTab('waiting')">
          <text class="tab-count">{{ contractStats.pending }}</text>
          <text class="tab-text">待签署</text>
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'pending' }" @click="switchTab('pending')">
          <text class="tab-count">{{ contractStats.executing }}</text>
          <text class="tab-text">待履约</text>
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'overdue' }" @click="switchTab('overdue')">
          <text class="tab-count warning">{{ contractStats.overdue }}</text>
          <text class="tab-text">已逾期</text>
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'completed' }" @click="switchTab('completed')">
          <text class="tab-count">{{ contractStats.completed }}</text>
          <text class="tab-text">已还清</text>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="search-section">
      <view class="search-box">
        <view class="search-icon">🔍</view>
        <input class="search-input" placeholder="请输入需要查询的名字" v-model="searchKeyword" @input="onSearchInput" />
      </view>
    </view>

    <!-- 合同列表 -->
    <view class="contract-list">
      <view class="list-header">
        <text class="list-title">合同列表</text>
      </view>

      <view class="contract-item" v-for="(item, index) in contractList" :key="index" @click="viewContract(item)">
        <!-- 合同头部 -->
        <view class="contract-header">
          <div class="header-left">
            <div class="role-badge" :class="getUserRole(item) === '债权人' ? 'lender' : 'borrower'">
              <text class="role-text">{{ getUserRole(item) }}</text>
            </div>
            <div class="amount-info">
              <text class="currency-symbol"> ¥</text>
              <text class="amount-value">{{ formatAmount(item.amount) }}</text>
            </div>
          </div>
          <div class="header-right">
            <text class="service-fee-text">平台服务费：¥{{ item.payAmount }}</text>
          </div>
        </view>
        <view class="contract-info">
            <div class="info-item">
              <text class="info-label" data-icon="👤">出借人</text>
                <text class="info-value">{{ item.lenderName || '-' }}</text>
            </div>
            <div class="info-item">
              <text class="info-label" data-icon="👥">借款人</text>
                <text class="info-value">{{ item.borrowerRealName || '-' }}</text>
            </div>
            <div class="info-item">
              <text class="info-label" data-icon="📆">合同起止日期</text>
                <text class="info-value">{{ item.startDate ? formatDate(item.startDate) : '-' }} - {{ item.endDate ? formatDate(item.endDate) : '-' }}</text>
            </div>
        </view>
            
        <!-- 合同主体信息 -->
        <view class="contract-body">
          <div class="info-grid">
      
            <div class="info-item">
              <text class="info-label" data-icon="💹">利息</text>
                <text class="info-value">{{ item.interest || 0 }}%</text>
            </div>
            <div class="info-item">
              <text class="info-label" data-icon="📅">期限</text>
                <text class="info-value">{{ item.duration }}天</text>
            </div>
            <div class="info-item" v-if="item.status !==5">
              <text class="info-label" data-icon="⚠️">逾期</text>
                <text class="info-value overdue">{{ item.overdueDays }}天</text>
            </div>
          </div>
        </view>

        <!-- 合同底部 -->
        <view class="contract-footer">
          <div class="status-info">
            <text class="tag priority" :class="{
              warning: item.payStatus == 2,
              success: item.payStatus == 3,
              info: item.payStatus == 1 || item.status == 5,
            }">{{
              statusMap[item.status == 5 ? item.status : item.payStatus]
            }}</text>
          </div>
          <div class="action-buttons">
            <view class="action-btn success" v-if="item.payStatus == 3 && item.status !== 5 && item.canOperate"
              @click.stop="extendContract(item)" :hover-stay-time="150">
              <text class="btn-text">展期</text>
            </view>
            <view class="action-btn warning" v-if="item.payStatus == 3 && item.status !== 5 && item.canOperate"
              @click.stop="closeContract(item)" :hover-stay-time="150">
              <text class="btn-text">消条</text>
            </view>
            <view class="action-btn danger" v-if="(item.payStatus <= 2 || item.status == 5) && item.canOperate"
              @click.stop="deleteContract(item)" :hover-stay-time="150">
              <text class="btn-text">删除</text>
            </view>
            <view class="action-btn primary" @click.stop="reviewContract(item)" :hover-stay-time="150">
              <text class="btn-text">查看详情</text>
            </view>
          </div>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!contractList.length && !isLoading">
        <text class="empty-icon">📄</text>
        <text class="empty-text">暂无相关合同</text>
      </view>

      <!-- 加载中状态 -->
      <view class="loading-state" v-if="isLoading && contractList.length">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 首次加载状态 -->
      <view class="first-loading" v-if="isLoading && !contractList.length">
        <view class="loading-spinner"></view>
        <text class="loading-text">正在获取合同数据...</text>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more-data" v-if="!hasMoreData && contractList.length && !isLoading">
        <text class="no-more-text">没有更多数据了</text>
      </view>
    </view>

    <!-- 展期弹窗 -->
    <uni-popup ref="refPopup" background-color="#fff">
      <view class="extend-contract-popup">
        <view class="popup-header">
          <text class="popup-title">合同展期</text>
        </view>
        <view class="popup-content">
          <!-- 合同信息展示 -->
          <view class="contract-info-section">
            <view class="info-row">
              <text class="info-label">合同金额</text>
              <text class="info-value">{{ formData.contractAmount }}元</text>
            </view>
            <view class="info-row">
              <text class="info-label">出借人</text>
              <text class="info-value">{{ formData.lenderName }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">借款人</text>
              <text class="info-value">{{ formData.borrowerRealName }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">开始时间</text>
              <text class="info-value">{{ formData.startDate }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">结束时间</text>
              <text class="info-value">{{ formData.endDate }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">利率</text>
              <text class="info-value">{{ formData.interestRate }}%</text>
            </view>
          </view>

          <!-- 展期时间选择 -->
          <view class="form-section">
            <view class="form-item">
              <text class="label required">截止日期时间</text>
              <view class="input-wrapper">
                <picker mode="date" :value="formData.extendEndDate" @change="onExtendDateChange"
                  :start="formatDateForPicker(formData.endDate)" :end="new Date(
                    new Date().setFullYear(new Date().getFullYear() + 1)
                  )
                      .toISOString()
                      .split('T')[0]
                    ">
                  <view class="uni-input" v-if="formData.extendEndDate">{{
                    formData.extendEndDate
                  }}</view>
                  <view v-else class="uni-input-tips">选择截止日期</view>
                </picker>
                <text class="arrow">›</text>
              </view>
            </view>
          </view>
          <view class="service-fee">
            <text class="fee-text" @click="updateChangeFiles">系统服务费:¥ 9.9 元
            </text>
          </view>
          <!-- 操作按钮 -->
          <view class="popup-actions">
            <button class="btn-cancel" @click="refPopup.value.close()">
              取消
            </button>
            <button class="btn-confirm" @click="confirmExtendContract">
              确认展期
            </button>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import request from "@/api/request.js";
import { onShow, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";

// 响应式数据
const refPopup = ref(null);
const activeTab = ref("all");
const searchKeyword = ref("");
const sortType = ref("time"); // time, amount
const sortOrder = ref("desc"); // desc, asc
const contractList = ref([]);
const userInfo = ref({
  lenderName: "",
  lenderIdCard: "",
});
const isLoggedIn = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const hasMoreData = ref(true);
const isLoading = ref(false);
const isExtendPopupVisible = ref(false);
const formData = ref({
  extendEndDate: "",
  contractAmount: "",
  lenderName: "",
  borrowerRealName: "",
  startDate: "",
  endDate: "",
  interestRate: "",
  contractId: "",
});
const statusMap = {
  1: "待确认",
  2: "待支付",
  3: "已支付",
  5: "已消条",
};
const contractStats = ref({
  completed: 0,
  executing: 0,
  overdue: 0,
  pending: 0,
  total: 0,
});

const fundOverview = ref({
  borrowedAmount: "0.00",
  lentAmount: "0.00",
  paidAmount: "0.00",
  payableAmount: "0.00",
  receivableAmount: "0.00",
  receivedAmount: "0.00",
});

const deleteContract = (e) => {
  uni.showModal({
    title: "提示",
    content: "确定要删除该合同吗？",
    success: async (res) => {
      if (res.confirm) {
        let res = await request.delete("/api/contracts/delete/" + e.id);
        if (res) {
          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
          // 刷新合同列表
          getContractList();
          getContractCount();
        } else {
          uni.showToast({
            title: res.msg || "删除失败",
            icon: "error",
          });
        }
      }
    },
  });
};
const closeContract = async (e) => {
  uni.showModal({
    title: "提示",
    content: "确定要终止该合同吗？",
    success: async (res) => {
      if (res.confirm) {
        const res = await request.put("/api/contracts/updateStatus/" + e.id, {
          status: 5,
        });
        console.log(res);
        if (res) {
          uni.showToast({
            title: "操作成功",
            icon: "success",
          });
          // 刷新合同列表
          getContractList();
          getContractCount();
        } else {
          uni.showToast({
            title: "操作失败，请重试",
            icon: "error",
          });
        }
      }
    },
  });
};
// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
  // 切换标签时重新加载第一页数据
  resetAndLoadData();
};

// 搜索输入
const onSearchInput = () => {
  // 搜索时重置页码并重新加载数据
  resetAndLoadData();
};

// 格式化金额
const formatAmount = (amount) => {
  return parseInt(amount).toLocaleString();
};

// 新增合同
const addContract = () => {
  if (!isLoggedIn.value) {
    uni.showModal({
      title: "提示",
      content: "请先登录后再创建合同",
      confirmText: "去登录",
      cancelText: "取消",
      success: (res) => {
        if (res.confirm) {
          goToLogin();
        }
      },
    });
    return;
  }
  uni.navigateTo({
    url: "/pages/borrow/identity",
  });
};

// 查看合同
const viewContract = (item) => {
  console.log("查看合同：", item);
};

// 合同详情
const reviewContract = (item) => {
  uni.navigateTo({
    url: "/pages/borrow/contractPreview?contractNumber=" + item.contractNumber,
  });
};

// 加载用户信息
const loadUserInfo = () => {
  const savedUserInfo = uni.getStorageSync("userInfo");
  if (savedUserInfo) {
    userInfo.value = { ...savedUserInfo };
    isLoggedIn.value = true;
  } else {
    isLoggedIn.value = false;
  }
};

// 跳转到登录页面
const goToLogin = () => {
  uni.navigateTo({
    url: "/pages/login/index",
  });
};
// 重置并加载数据
const resetAndLoadData = () => {
  currentPage.value = 1;
  hasMoreData.value = true;
  contractList.value = [];
  getContractList();
};

// 获取统计数据
const getContractCount = async () => {
  if (!isLoggedIn.value) return;
  let res = await request.get("/api/contracts/dashboard");
  if (res.code === 200) {
    console.log(res.data);
    contractStats.value = res.data.contractStats;
    fundOverview.value = res.data.fundOverview;
  }
};

// 展期
const extendContract = (item) => {
  // 弹窗出现合同基础信息
  if (refPopup.value && typeof refPopup.value.open === "function") {
    refPopup.value.open();
    // 设置合同数据到formData
    formData.value = {
      extendEndDate: "",
      contractAmount: item.amount || "",
      lenderName: item.lenderName || "",
      borrowerRealName: item.borrowerRealName || "",
      startDate: item.startDate || "",
      endDate: item.endDate || "",
      interestRate: item.interestRate || "",
      contractId: item.id || "",
    };
  } else {
    console.error("无法打开弹窗，refPopup未正确初始化");
    uni.showToast({
      title: "无法打开弹窗，请稍后重试",
      icon: "error",
    });
  }
};

// 判断用户在合同中的角色（债权人/债务人）
const getUserRole = (item) => {
  if (!isLoggedIn.value || !userInfo.value.realName) return '';
  console.log(userInfo.value.realName);
  // 比较当前登录用户的姓名与合同中的出借人和借款人信息
  if (userInfo.value.realName === item.lenderName) {
    return '债权人' 
  } else if (userInfo.value.realName === item.borrowerRealName) {
    return '债务人'
  }
  return ''; // 如果都不匹配，则返回空
};

// 格式化日期为选择器需要的格式
const formatDateForPicker = (dateString) => {
  if (!dateString) return "";
  // 尝试多种日期格式解析
  const date = new Date(dateString);
  if (!isNaN(date.getTime())) {
    // 确保格式为YYYY-MM-DD
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  }
  return dateString;
};

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return "";
  // 尝试多种日期格式解析
  const date = new Date(dateString);
  if (!isNaN(date.getTime())) {
    // 确保格式为YYYY-MM-DD
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  }
  return dateString;
};

// 展期时间变更
const onExtendDateChange = (e) => {
  formData.value.extendEndDate = e.detail.value;
};

const confirmExtendContract = async () => {
  if (!formData.value.extendEndDate) {
    uni.showToast({
      title: "请选择展期时间",
      icon: "error",
    });
    return;
  }

  // 验证选择的日期不小于合同结束日期
  const selectedDate = new Date(formData.value.extendEndDate);
  const contractEndDate = new Date(formData.value.endDate);

  if (selectedDate < contractEndDate) {
    uni.showToast({
      title: "选择的日期不能小于合同结束日期",
      icon: "error",
    });
    return;
  }

  // 调用展期接口
  const res = await request.put(
    "/api/contracts/extend/" + formData.value.contractId,
    formData.value
  );
  if (res) {
    uni.showToast({
      title: "展期成功,点击详情查看",
      icon: "success",
    });
    // 关闭弹窗
    refPopup.value.close();
    // 跳转到合同详情
    uni.navigateTo({
      url:
        "/pages/borrow/contractPreview?contractNumber=" + item.contractNumber,
    });
  } else {
    uni.showToast({
      title: res.msg || "展期失败",
      icon: "error",
    });
  }
};
// 获取合同列表
const getContractList = async (isLoadMore = false) => {
  if (!isLoggedIn.value || isLoading.value) return;

  isLoading.value = true;
  try {
    // 构建请求参数
    const params = {
      page: isLoadMore ? currentPage.value : 1,
      limit: pageSize.value,
      status: activeTab.value === "all" ? "" : activeTab.value,
      search: searchKeyword.value,
      sortType: sortType.value,
      sortOrder: sortOrder.value,
    };

    // 将参数转换为查询字符串
    const queryString = Object.entries(params)
      .filter(([key, value]) => value !== "" && value !== undefined)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join("&");

    let res = await request.get(`/api/contracts/list?${queryString}`);
    if (res.code === 200) {
      console.log(res.data);
      if (isLoadMore) {
        // 加载更多时追加数据
        contractList.value = [...contractList.value, ...res.data.contracts];
        // 判断是否还有更多数据
        hasMoreData.value = res.data.contracts.length === pageSize.value;
        if (hasMoreData.value) {
          currentPage.value++;
        }
      } else {
        // 首次加载或刷新时替换数据
        contractList.value = res.data.contracts;
        // 重置页码
        currentPage.value = 2;
        // 判断是否有更多数据
        hasMoreData.value = res.data.contracts.length === pageSize.value;
      }
    }
  } catch (error) {
    console.error("获取合同列表失败:", error);
    uni.showToast({
      title: "获取合同列表失败",
      icon: "error",
    });
  } finally {
    isLoading.value = false;
    // 停止下拉刷新动画
    uni.stopPullDownRefresh();
  }
};

// 下拉刷新
onPullDownRefresh(() => {
  if (isLoggedIn.value) {
    // 刷新统计数据
    getContractCount();
    // 刷新合同列表（不加载更多）
    getContractList(false);
  } else {
    // 未登录时也停止下拉刷新动画
    uni.stopPullDownRefresh();
  }
});

// 上拉加载更多
onReachBottom(() => {
  if (isLoggedIn.value && hasMoreData.value && !isLoading.value) {
    getContractList(true);
  }
});

onShow(() => {
  // 初始化
  loadUserInfo();
  if (isLoggedIn.value) {
    getContractList();
    getContractCount();
  }
});
</script>

<style>
.container {
  background: linear-gradient(180deg, #f8fafc 0%, #e2e8f0 100%);
}

/* 顶部卡片优化 */
.top-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 50rpx 30rpx 60rpx;
  position: relative;
  overflow: hidden;
}

/* 加载状态样式 */
.loading-state,
.first-loading,
.no-more-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
  color: #666;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-text,
.no-more-text {
  font-size: 28rpx;
  color: #999;
}

.decoration-bg {
  position: absolute;
  top: -50%;
  right: -20%;
  width: 300rpx;
  height: 300rpx;
  background: radial-gradient(circle,
      rgba(255, 255, 255, 0.1) 0%,
      transparent 70%);
  border-radius: 50%;
  pointer-events: none;
}

/* 返佣模式开关优化 */
.rebate-switch {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 50rpx;
  padding: 25rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20rpx;
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.switch-content {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.switch-label {
  font-size: 32rpx;
  color: #fff;
  font-weight: 600;
}

.switch-desc {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.custom-switch {
  transform: scale(1.2);
}

/* 用户信息优化 */
.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 50rpx;
}

.user-left {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-left:active {
  transform: scale(0.98);
  opacity: 0.8;
}

.user-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50rpx;
  background: linear-gradient(135deg, #fff 0%, #f8fafc 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.15);
  position: relative;
  margin-right: 25rpx;
}

.avatar-text {
  font-size: 36rpx;
  color: #667eea;
  font-weight: 700;
}

.avatar-badge {
  position: absolute;
  bottom: 5rpx;
  right: 5rpx;
  width: 20rpx;
  height: 20rpx;
  background: #10b981;
  border-radius: 50%;
  border: 3rpx solid #fff;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.username {
  font-size: 36rpx;
  color: #fff;
  font-weight: 700;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.user-level {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.contract-action {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 15rpx 25rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.contract-action:active {
  transform: scale(0.95);
}

.action-icon {
  font-size: 28rpx;
  color: #667eea;
  font-weight: bold;
}

.action-text {
  font-size: 26rpx;
  color: #667eea;
  font-weight: 600;
}

/* 金额统计优化 */
.amount-stats {
  background: rgba(255, 255, 255, 0.98);
  border-radius: 25rpx;
  padding: 35rpx;
  margin: 0 -5rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.1), 0 8rpx 25rpx rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(20rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.stats-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #e2e8f0;
}

.stats-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #1e293b;
}

.stats-update {
  font-size: 22rpx;
  color: #10b981;
  background: #dcfce7;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 35rpx;
}

.amount-row:last-child {
  margin-bottom: 0;
}

.amount-row.detail {
  padding-top: 25rpx;
  border-top: 1rpx solid #f1f5f9;
}

.amount-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  position: relative;
}

.amount-item.main {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 20rpx;
  padding: 10rpx;
  background: #f8fafc;
  border-radius: 20rpx;
}

.amount-item.small {
  flex: 0.25;
  padding: 20rpx 10rpx;
}

.amount-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.amount-icon.lend {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.amount-icon.borrow {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
}

.amount-content {
  display: flex;
  flex-direction: column;
  gap: 5rpx;
}

.amount-value {
  font-size: 36rpx;
  font-weight: 800;
  color: #1e293b;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
}

.amount-label {
  font-size: 24rpx;
  color: #64748b;
  font-weight: 500;
}

.small-value {
  font-size: 26rpx;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 8rpx;
}

.small-value.red {
  color: #dc2626;
}

.small-value.green {
  color: #059669;
}

.small-label {
  font-size: 20rpx;
  color: #64748b;
  margin-bottom: 10rpx;
}

/* 合同标签优化 */
.contract-tabs {
  background: #fff;
  padding: 0;
}

.tabs-scroll {
  white-space: nowrap;
  padding: 0 20rpx;
  display: flex;
  justify-content: space-between;
}

.tab-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  padding: 25rpx 20rpx;
  position: relative;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #667eea;
}

.tab-text {
  font-size: 28rpx;
  color: #4a5568;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-top: 10rpx;
}

.tab-item.active .tab-text {
  color: #667eea;
  font-weight: 700;
}

.tab-count {
  font-size: 22rpx;
  color: #64748b;
  background: #f1f5f9;
  padding: 4rpx 10rpx;
  border-radius: 10rpx;
  min-width: 30rpx;
  text-align: center;
  transition: all 0.3s ease;
}

.tab-item.active .tab-count {
  background: #667eea;
  color: #fff;
}

.tab-count.warning {
  background: #fef3c7;
  color: #d97706;
}

.tab-item.active .tab-count.warning {
  background: #d97706;
  color: #fff;
}

/* 搜索和筛选优化 */
.search-section {
  padding: 25rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #e2e8f0;
}

.search-box {
  display: flex;
  align-items: center;
  background: #f8fafc;
  border-radius: 25rpx;
  padding: 0 25rpx;
  border: 1rpx solid #e2e8f0;
  transition: all 0.3s ease;
}

.search-box:focus-within {
  border-color: #667eea;
  background: #fff;
  box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
}

.search-icon {
  font-size: 28rpx;
  color: #64748b;
  margin-right: 15rpx;
}

.search-input {
  flex: 1;
  height: 70rpx;
  font-size: 28rpx;
  color: #1e293b;
  background: transparent;
  border: none;
}

/* 合同列表优化 */
.contract-list {
  padding: 0 30rpx;
  background: #fff;
}

.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0 20rpx;
}

.list-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #1e293b;
}

.sort-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background: #f8fafc;
  border-radius: 20rpx;
  border: 1rpx solid #e2e8f0;
  transition: all 0.3s ease;
}

.sort-btn:active {
  background: #e2e8f0;
}

.sort-text {
  font-size: 24rpx;
  color: #64748b;
}

.sort-icon {
  font-size: 20rpx;
  color: #64748b;
}

.contract-item {
  margin-bottom: 24rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}


.contract-left {
  flex: 1;
  margin-right: 20rpx;
}

.contract-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1e293b;
  line-height: 1.4;
  margin-bottom: 12rpx;
}

.contract-tags {
  display: flex;
  gap: 10rpx;
  flex-wrap: wrap;
}

.tag {
  font-size: 20rpx;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-weight: 500;
}

.tag.overdue {
  color: #dc2626;
  background: #fef2f2;
  border: 1rpx solid #fecaca;
}

.tag.warning {
  color: #d97706;
  background: #fef3c7;
  border: 1rpx solid #fed7aa;
}

.tag.success {
  color: #16a34a;
  background: #dcfce7;
  border: 1rpx solid #bbf7d0;
}

.tag.info {
  color: #666;
  background: #d3d2d2;
  border: 1rpx solid #eee;
}

.contract-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.role-badge {
  padding: 6rpx 16rpx;
  border-radius: 18rpx;
  font-size: 24rpx;
  font-weight: 600;
}

.role-badge.lender {
  background-color: #e0f2fe;
  color: #0ea5e9;
}

.role-badge.borrower {
  background-color: #fef3c7;
  color: #f59e0b;
}

.amount-info {
  display: flex;
  align-items: baseline;
  gap: 4rpx;
}

.currency-symbol {
  font-size: 28rpx;
  color: #1e293b;
}

.amount-value {
  font-size: 32rpx;
  color: #1e293b;
  letter-spacing: 1rpx;
}

.header-right {
  display: flex;
  align-items: center;
}

.service-fee-text {
  font-size: 24rpx;
  color: #64748b;
  font-family: monospace;
}

.contract-body {
  margin-bottom: 25rpx;
  padding: 20rpx 0;
  border-top: 1rpx solid #f1f5f9;
  border-bottom: 1rpx solid #f1f5f9;
}

.info-grid {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10rpx;
  flex: 1;
  text-align: center;
  padding: 10rpx;
  border-radius: 12rpx;
  transition: background-color 0.2s ease;
}

.info-item:active {
  background-color: #f8fafc;
}

.info-label {
  font-size: 24rpx;
  color: #64748b;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.info-label::before {
  content: attr(data-icon);
  font-size: 20rpx;
}

.info-value {
  font-size: 28rpx;
  color: #1e293b;
}

.info-value.overdue {
  color: #dc2626;
  font-weight: 700;
}

.info-value.overdue {
  color: #dc2626;
}

/* 合同信息容器样式优化 */
.contract-info {
  /* margin-bottom: 25rpx; */
}

.contract-info .info-grid {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.contract-info .info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
  text-align: left;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #e2e8f0;
  transition: all 0.2s ease;
}

.contract-info .info-item:last-child {
  border-bottom: none;
}

.contract-info .info-label {
  font-size: 26rpx;
  color: #64748b;
  min-width: 120rpx;
}

.contract-info .info-value {
  font-size: 28rpx;
  color: #4d535e;
  text-align: right;
  flex: 1;
  word-break: break-all;
}

.timeline {
  padding: 15rpx 20rpx;
  border-radius: 12rpx;
}

.timeline-text {
  font-size: 24rpx;
  color: #64748b;
  font-family: monospace;
}

.contract-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 20rpx;
  border-top: 1rpx solid #f1f5f9;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex: 1;
}

.status-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #10b981;
}

.status-dot.overdue {
  background: #dc2626;
  animation: blink 2s infinite;
}

@keyframes blink {

  0%,
  50% {
    opacity: 1;
  }

  51%,
  100% {
    opacity: 0.3;
  }
}

.status-text {
  font-size: 24rpx;
  color: #64748b;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.action-btn {
  border-radius: 18rpx;
  transition: all 0.3s ease;
  color: #fff;
  padding: 12rpx 24rpx;
}

.action-btn.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.action-btn.success {
  background: #16a34a;
}

.action-btn.warning {
  background: #d97706;
}

.action-btn.danger {
  background: #dc2626;
}

.action-btn.secondary {
  background: #f8fafc;
  border: 1rpx solid #e2e8f0;
}

.action-btn.primary .btn-text {
  color: #fff;
}

.action-btn.secondary .btn-text {
  color: #64748b;
}

.btn-text {
  font-size: 24rpx;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 40rpx;
  text-align: center;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 32rpx;
  color: #64748b;
  font-weight: 600;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #94a3b8;
}

/* 展期弹窗样式 */
.extend-contract-popup {
  width: 700rpx;
  background-color: #fff;
  overflow: hidden;
  box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  position: relative;
}

/* 弹窗装饰元素 */
.extend-contract-popup::before {
  content: "";
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200rpx;
  height: 200rpx;
  background: radial-gradient(circle,
      rgba(102, 126, 234, 0.05) 0%,
      transparent 70%);
  border-radius: 50%;
  z-index: 0;
}

.popup-header {
  padding: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  text-align: center;
  position: relative;
  overflow: hidden;
}

/* 头部装饰元素 */
.popup-header::after {
  content: "";
  position: absolute;
  bottom: -20rpx;
  right: -20rpx;
  width: 100rpx;
  height: 100rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.popup-header::before {
  content: "";
  position: absolute;
  top: -20rpx;
  left: 30%;
  width: 60rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 50%;
}

.popup-title {
  color: #fff;
  font-size: 36rpx;
  font-weight: 600;
  position: relative;
  z-index: 1;
  letter-spacing: 2rpx;
}

.popup-content {
  padding: 32rpx;
  position: relative;
  z-index: 1;
}

/* 合同信息部分 */
.contract-info-section {
  margin-bottom: 32rpx;
  padding: 24rpx;
  background-color: #f8fafc;
  border-radius: 16rpx;
  border: 1rpx solid #e2e8f0;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #e2e8f0;
  transition: background-color 0.2s ease;
}

.info-row:hover {
  background-color: rgba(102, 126, 234, 0.03);
  border-radius: 8rpx;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #64748b;
  font-weight: 500;
  display: flex;
  align-items: center;
}

/* 为标签添加小图标 */
.info-row:nth-child(1) .info-label::before {
  content: "💰";
  margin-right: 10rpx;
  font-size: 24rpx;
}

.info-row:nth-child(2) .info-label::before {
  content: "👤";
  margin-right: 10rpx;
  font-size: 24rpx;
}

.info-row:nth-child(3) .info-label::before {
  content: "👥";
  margin-right: 10rpx;
  font-size: 24rpx;
}

.info-row:nth-child(4) .info-label::before {
  content: "📅";
  margin-right: 10rpx;
  font-size: 24rpx;
}

.info-row:nth-child(5) .info-label::before {
  content: "⏰";
  margin-right: 10rpx;
  font-size: 24rpx;
}

.info-row:nth-child(6) .info-label::before {
  content: "📊";
  margin-right: 10rpx;
  font-size: 24rpx;
}

.info-value {
  font-size: 28rpx;
  color: #1e293b;
  text-align: right;
}

/* 金额和利率高亮显示 */
.info-row:nth-child(1) .info-value,
.info-row:nth-child(6) .info-value {
  color: #667eea;
  letter-spacing: 1rpx;
}

/* 表单部分 */
.form-section {
  margin-bottom: 32rpx;
}

.form-item {
  margin-bottom: 28rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #64748b;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.label.required::after {
  content: "*";
  color: #ef4444;
  margin-left: 5rpx;
}

.input-wrapper {
  position: relative;
  border-radius: 12rpx;
  overflow: hidden;
  transition: all 0.3s ease;
}


.uni-input,
.uni-input-tips {
  padding: 22rpx;
  font-size: 28rpx;
  color: #1e293b;
}

.uni-input-tips {
  color: #94a3b8;
}

.arrow {
  position: absolute;
  right: 22rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #94a3b8;
  font-size: 24rpx;
  transition: all 0.3s ease;
}

/* 操作按钮 */
.popup-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 24rpx;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 12rpx;
  border: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  letter-spacing: 2rpx;
  position: relative;
  overflow: hidden;
}

/* 按钮点击效果 */
.btn-cancel::before,
.btn-confirm::before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg,
      transparent,
      rgba(255, 255, 255, 0.2),
      transparent);
  transition: all 0.6s ease;
}

.btn-cancel:active::before,
.btn-confirm:active::before {
  left: 100%;
}

.btn-cancel {
  background-color: #f8fafc;
  color: #64748b;
  border: 1rpx solid #e2e8f0;
}

.btn-cancel:active {
  background-color: #f1f5f9;
  transform: scale(0.98);
  box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.btn-confirm {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.btn-confirm:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.25);
}

/* 增强的确认按钮效果 */
.btn-confirm:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}

/* 未登录状态的置灰效果 */
.btn-confirm:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-confirm:disabled:active {
  transform: none;
}

/* 响应式优化 */
@media (max-width: 750rpx) {
  .top-card {
    padding: 40rpx 20rpx 50rpx;
  }

  .amount-stats {
    padding: 25rpx;
    margin: 0;
  }

  .contract-list {
    padding: 0 20rpx;
  }

  .contract-item {
    padding: 25rpx;
  }

  .amount-item.main {
    flex-direction: column;
    gap: 10rpx;
    padding: 10rpx;
  }

  .info-grid {
    flex-wrap: wrap;
    gap: 15rpx;
  }

  .info-item {
    flex: 0 0 calc(50% - 7.5rpx);
  }

  /* 弹窗响应式优化 */
  .extend-contract-popup {
    width: 95%;
    border-radius: 20rpx;
    box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.12);
  }

  .popup-header {
    padding: 28rpx;
  }

  .popup-content {
    padding: 28rpx;
  }

  /* 合同信息部分响应式 */
  .contract-info-section {
    padding: 20rpx;
    margin-bottom: 28rpx;
    border-radius: 12rpx;
  }

  .info-row {
    padding: 12rpx 0;
  }

  .info-row:hover {
    border-radius: 6rpx;
  }

  /* 标签图标响应式调整 */
  .info-label::before {
    margin-right: 8rpx;
    font-size: 22rpx !important;
  }

  .info-label,
  .info-value,
  .label {
    font-size: 26rpx;
  }

  /* 金额和利率高亮效果响应式 */
  .info-row:nth-child(1) .info-value,
  .info-row:nth-child(6) .info-value {
    letter-spacing: 0.5rpx;
  }

  /* 表单部分响应式 */
  .form-section {
    margin-bottom: 28rpx;
  }

  .form-item {
    margin-bottom: 24rpx;
  }

  .input-wrapper {
    border-radius: 10rpx;
  }

  .uni-input,
  .uni-input-tips {
    padding: 20rpx;
    font-size: 26rpx;
  }

  .arrow {
    right: 20rpx;
    font-size: 22rpx;
  }

  /* 按钮响应式调整 */
  .popup-actions {
    margin-top: 20rpx;
    gap: 16rpx;
  }

  .btn-cancel,
  .btn-confirm {
    font-size: 30rpx;
    padding: 20rpx;
    border-radius: 10rpx;
    letter-spacing: 1rpx;
  }

  .btn-confirm {
    box-shadow: 0 3rpx 10rpx rgba(102, 126, 234, 0.25);
  }

  /* 简化装饰元素在小屏幕上的显示 */
  .extend-contract-popup::before,
  .popup-header::after,
  .popup-header::before {
    transform: scale(0.8);
  }
}
.text-l{
  font-size: 28rpx;
  color: #1e293b;


}
.service-fee {
  text-align: right;
  margin-top: 20rpx;
}

.fee-text {
  font-size: 26rpx;
  color: #667eea;
}
</style>
